package teacher

import (
	"github.com/gin-gonic/gin"
	"github.com/go-playground/validator/v10"
	"go.uber.org/zap"
	"project/pkg/jwt"
	"project/pkg/md5"
	"project/pkg/models"
	"project/pkg/validate"
)

func (h THandler) Login(c *gin.Context) {
	resp := new(models.RespData)
	req := new(models.TeacherLoginReq)
	if err := c.ShouldBindJSON(req); err != nil {
		errs, ok := err.(validator.ValidationErrors)
		if !ok {
			zap.L().Error("Student:Login with invalid fail", zap.Error(err))
			resp.SendServerBusy(c)
			return
		} else {
			zap.L().Error("Student:Login with invalid fail", zap.Error(errs))
			resp.SendCodeWithMsg(c, models.CodeInvalidParam, validate.RemoveTopStruct(errs.Translate(validate.Trans)))
			return
		}
	}
	//检查用户
	exist, info, err := h.M.TeacherCheckExist(req.Username)
	if err != nil {
		zap.L().Error("Student:UpdateInfo h.M.TeacherCheckExist err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	if !exist {
		resp.SendCode(c, models.CodeUserNotExist)
		return
	}
	if !md5.Compare(info.Password, req.Password) {
		resp.SendCode(c, models.CodeInvalidPassword)
		return
	}
	token, err := jwt.GenToken(info.ID, info.Username, info.Name)
	if err != nil {
		zap.L().Error("Student:UpdateInfo jwt.GenToken err", zap.Error(err))
		resp.SendServerBusy(c)
		return
	}
	resp.Data = gin.H{
		"token":    token,
		"name":     info.Name,
		"username": info.ID,
	}
	resp.SendSuccess(c)
}
